<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/2/24
 * Time: 16:56
 */

namespace SDXApi\Service;


use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Model\HomeTemplateStencilSeminarModel;
use SDXApi\Model\SeminarModel;

/**
 * Class HomeTemplateSeminarService
 * @package SDXApi\Service
 */
class HomeTemplateSeminarService extends TemplateAbstract
{
	/**
	 * @var HomeTemplateStencilSeminarModel
	 */
	protected $templateStencilSeminarModel;

	/**
	 * @var SeminarModel
	 */
	protected $seminarModel;

	/**
	 * HomeTemplateSeminarService constructor.
	 */
	public function __construct()
	{
		$this->templateStencilSeminarModel = new HomeTemplateStencilSeminarModel();
		$this->seminarModel = new SeminarModel();
	}

	/**
	 * Created by Jerry
	 * @param array $stencil
	 * @param int $userId
	 * @param int $wid
	 * @return array|bool
	 */
	public function handle($stencil = array(), $userId = 0, $wid = 8)
	{
		$cacheName = 'home_template_seminar_id_' . $stencil['id'];

//		获取缓存
		$data = $this->getCache($cacheName);

		if (empty($data)) {
			$data = $this->stencilSeminar($stencil, $userId, $wid);
			$this->cacheData($cacheName, $data, mt_rand(3600, 4200));
		}

		return $data;
	}

	/**
	 * 处理专题数据
	 * Created by Jerry
	 * @param array $stencil
	 * @param int $userId
	 * @param int $wid
	 * @return array|bool
	 */
	protected function stencilSeminar($stencil = array(), $userId = 0, $wid = 8)
	{
		$stencils = $this->findTemplateStencilSeminarByStencilId($stencil['id']);

		if (empty($stencils)) {
			return false;
		}

		foreach ($stencils as $key => $value) {
			$stencil['size'] = $value['size'];
			$data = $this->findTemplateStencilSeminarForSeminarById($value['seminar_id']);

			if (empty($data)) {
				continue;
			}

			$data['image'] = self::checkImageUrlReplace($data['image']);

			$data['sort'] = $value['sort'];

			$stencil['seminar_list'][] = $data;
		}

		if (empty($stencil['seminar_list'])) {
			return false;
		}

		return $stencil;
	}

	/**
	 * Created by Jerry
	 * @param $stencilId
	 * @return array|mixed
	 */
	protected function findTemplateStencilSeminarByStencilId($stencilId)
	{
		$data = $this->templateStencilSeminarModel->find_seminars_by_stencil_id($stencilId);
		if (empty($data)) {
			$data = array();
		}

		return $data;
	}

	/**
	 * 返回专题
	 * Created by Jerry
	 * @param $id
	 * @return mixed
	 */
	protected function findTemplateStencilSeminarForSeminarById($id)
	{
		return $this->seminarModel->find_seminar_template_by_id($id);
	}

	/**
	 * 处理专题图片
	 * Created by Jerry
	 * @param $url
	 * @return mixed
	 */
	protected static function checkImageUrlReplace($url)
	{

		$urlPos = strpos($url, '//oss.shidexian.com');
		if ($urlPos !== false) {
			$url = str_replace('//oss.', 'https://image.', $url);
		}

		return $url;
	}
}